package com.gitee.apanlh.util.net.http.io;

import com.gitee.apanlh.util.io.IOUtils;
import com.gitee.apanlh.util.net.http.HttpClient;
import com.gitee.apanlh.util.net.http.HttpStatus;
import com.gitee.apanlh.util.valid.ValidParam;

import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;

/**		
 * 	 响应流类型
 * 		
 * 	@author Pan
 */
public class HttpResponseInputStream extends InputStream implements Closeable {
	
	/** 原始流 */
	private InputStream inputStream;
	/** 成功输入流 */
	private HttpOkInputStream okInputStream;
	/** 错误输入流 */
    private HttpErrorInputStream errorInputStream;
    
    /**
     * 	构造函数-初始化加载流
     * 	
     * 	@author Pan
     * 	@param 	httpClient	HTTP客户端
     * 	@param 	httpStatus	HTTP状态
     */
    public HttpResponseInputStream(HttpClient httpClient, HttpStatus httpStatus) {
    	//  检查状态
    	if (httpStatus.isError()) {
    		this.inputStream = httpClient.getErrorInputStream();
    		this.errorInputStream = new HttpErrorInputStream(this.inputStream);
    	} else {
    		this.inputStream = httpClient.getInputStream();
    		this.okInputStream = new HttpOkInputStream(this.inputStream);
    	}
    }

	/**	
	 * 	获取响应成功输入流
	 * 	
	 * 	@author Pan
	 * 	@return	HttpOkInputStream
	 */
	public HttpOkInputStream getOkInputStream() {
		return okInputStream;
	}

	/**	
	 * 	获取响应失败输入流
	 * 	
	 * 	@author Pan
	 * 	@return	HttpErrorInputStream
	 */
	public HttpErrorInputStream getErrorInputStream() {
		return errorInputStream;
	}
	
	@Override
	public int read() throws IOException {
		return inputStream.read();
	}
	
	@Override
	public int read(byte[] b, int off, int len) throws IOException {
		return inputStream.read(b, off, len);
	}
	
	/**
	 * 	读取响应
	 * 	<br>默认自动关闭输入流
	 * 	
	 * 	@author Pan
	 * 	@return	byte[]
	 */
	public byte[] readResponse() {
		return IOUtils.read(inputStream);
	}
	
	/**	
	 * 	是否为成功响应输入流
	 * 	
	 * 	@author Pan
	 * 	@return	boolean
	 */
	public boolean hasOkInputStream() {
		return ValidParam.isNotNull(okInputStream);
	}
	
	/**	
	 * 	是否为错误响应输入流
	 * 	
	 * 	@author Pan
	 * 	@return	boolean
	 */
	public boolean hasErrorInputStream() {
		return ValidParam.isNotNull(errorInputStream);
	}
	
	@Override
	public void close() throws IOException {
		inputStream.close();
	}
}
